home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1994 / MacHack 1994.toast / MacHack™ 1987-1994 / MacHack™ '92 / Hacks ’92 / Procedure Call Logger / Sample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-06-18  |  30.2 KB  |  886 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.c    -    C Source
  10. #
  11. #    Copyright © Apple Computer, Inc. 1989-1990
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89    MPW 3.1
  18. #                1.03                02/90    MPW 3.2
  19. #
  20. #    Components:
  21. #                Sample.c            Feb.  1, 1990
  22. #                Sample.r            Feb.  1, 1990
  23. #                Sample.h            Feb.  1, 1990
  24. #                Sample.make            Feb.  1, 1990
  25. #
  26. #    Sample is an example application that demonstrates how to
  27. #    initialize the commonly used toolbox managers, operate 
  28. #    successfully under MultiFinder, handle desk accessories, 
  29. #    and create, grow, and zoom windows.
  30. #
  31. #    It does not by any means demonstrate all the techniques 
  32. #    you need for a large application. In particular, Sample 
  33. #    does not cover exception handling, multiple windows/documents, 
  34. #    sophisticated memory management, printing, or undo. All of 
  35. #    these are vital parts of a normal full-sized application.
  36. #
  37. #    This application is an example of the form of a Macintosh 
  38. #    application; it is NOT a template. It is NOT intended to be 
  39. #    used as a foundation for the next world-class, best-selling, 
  40. #    600K application. A stick figure drawing of the human body may 
  41. #    be a good example of the form for a painting, but that does not 
  42. #    mean it should be used as the basis for the next Mona Lisa.
  43. #
  44. #    We recommend that you review this program or TESample before 
  45. #    beginning a new application.
  46. #
  47. ------------------------------------------------------------------------------*/
  48.  
  49.  
  50. /* Segmentation strategy:
  51.  
  52.    This program consists of three segments. Main contains most of the code,
  53.    including the MPW libraries, and the main program. Initialize contains
  54.    code that is only used once, during startup, and can be unloaded after the
  55.    program starts. %A5Init is automatically created by the Linker to initialize
  56.    globals for the MPW libraries and is unloaded right away. */
  57.  
  58.  
  59. /* SetPort strategy:
  60.  
  61.    Toolbox routines do not change the current port. In spite of this, in this
  62.    program we use a strategy of calling SetPort whenever we want to draw or
  63.    make calls which depend on the current port. This makes us less vulnerable
  64.    to bugs in other software which might alter the current port (such as the
  65.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  66.    Hopefully, this also makes the routines from this program more self-contained,
  67.    since they don't depend on the current port setting. */
  68.  
  69.  
  70. #include <Values.h>
  71. #include <Types.h>
  72. #include <Resources.h>
  73. #include <QuickDraw.h>
  74. #include <Fonts.h>
  75. #include <Events.h>
  76. #include <Windows.h>
  77. #include <Menus.h>
  78. #include <TextEdit.h>
  79. #include <Dialogs.h>
  80. #include <Desk.h>
  81. #include <ToolUtils.h>
  82. #include <Memory.h>
  83. #include <SegLoad.h>
  84. #include <Files.h>
  85. #include <OSUtils.h>
  86. #include <OSEvents.h>
  87. #include <DiskInit.h>
  88. #include <Packages.h>
  89. #include <Traps.h>
  90. #include "Sample.h"        /* bring in all the #defines for Sample */
  91.  
  92. #include <BP_EP.h>
  93.  
  94. /* The "g" prefix is used to emphasize that a variable is global. */
  95.  
  96. /* GMac is used to hold the result of a SysEnvirons call. This makes
  97.    it convenient for any routine to check the environment. */
  98. SysEnvRec    gMac;                /* set up by Initialize */
  99.  
  100. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  101.    trap is available. If it is false, we know that we must call GetNextEvent. */
  102. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  103.  
  104. /* GInBackground is maintained by our osEvent handling routines. Any part of
  105.    the program can check it to find out if it is currently in the background. */
  106. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  107.  
  108.  
  109. /* The following globals are the state of the window. If we supported more than
  110.    one window, they would be attatched to each document, rather than globals. */
  111.  
  112. /* GStopped tells whether the stop light is currently on stop or go. */
  113. Boolean        gStopped;            /* maintained by Initialize and SetLight */
  114.  
  115. /* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
  116. Rect        gStopRect;            /* set up by Initialize */
  117. Rect        gGoRect;            /* set up by Initialize */
  118.  
  119.  
  120. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  121.    actual prototypes for parameter type checking. */
  122. void EventLoop( void );
  123. void DoEvent( EventRecord *event );
  124. void AdjustCursor( Point mouse, RgnHandle region );
  125. void GetGlobalMouse( Point *mouse );
  126. void DoUpdate( WindowPtr window );
  127. void DoActivate( WindowPtr window, Boolean becomingActive );
  128. void DoContentClick( WindowPtr window );
  129. void DrawWindow( WindowPtr window );
  130. void AdjustMenus( void );
  131. void DoMenuCommand( long menuResult );
  132. void SetLight( WindowPtr window, Boolean newStopped );
  133. Boolean DoCloseWindow( WindowPtr window );
  134. void Terminate( void );
  135. void Initialize( void );
  136. Boolean GoGetRect( short rectID, Rect *theRect );
  137. void ForceEnvirons( void );
  138. Boolean IsAppWindow( WindowPtr window );
  139. Boolean IsDAWindow( WindowPtr window );
  140. Boolean TrapAvailable( short tNumber, TrapType tType );
  141. void AlertUser( void );
  142.  
  143.  
  144. /* Define HiWrd and LoWrd macros for efficiency. */
  145. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  146. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  147.  
  148. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  149.    dependency on the ordering of fields within a Rect */
  150. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  151. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  152.  
  153.  
  154. extern void _DataInit();
  155.  
  156. /* This routine is part of the MPW runtime library. This external
  157.    reference to it is done so that we can unload its segment, %A5Init. */
  158.  
  159.  
  160. #pragma segment Main
  161. main()
  162. {
  163.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  164.     
  165.     /* 1.01 - call to ForceEnvirons removed */
  166.     
  167.     /*    If you have stack requirements that differ from the default,
  168.         then you could use SetApplLimit to increase StackSpace at 
  169.         this point, before calling MaxApplZone. */
  170.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  171.  
  172.     Initialize();                    /* initialize the program */
  173.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  174.  
  175.     EventLoop();                    /* call the main event loop */
  176. }
  177.  
  178.  
  179. /*    Get events forever, and handle them by calling DoEvent.
  180.     Get the events by calling WaitNextEvent, if it's available, otherwise
  181.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  182.  
  183. #pragma segment Main
  184. void EventLoop()
  185. {
  186.     RgnHandle    cursorRgn;
  187.     Boolean        gotEvent;
  188.     EventRecord    event;
  189.     Point        mouse;
  190.  
  191.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  192.     do {
  193.         /* use WNE if it is available */
  194.         if ( gHasWaitNextEvent ) {
  195.             GetGlobalMouse(&mouse);
  196.             AdjustCursor(mouse, cursorRgn);
  197.             gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  198.         }
  199.         else {
  200.             SystemTask();
  201.             gotEvent = GetNextEvent(everyEvent, &event);
  202.         }
  203.         if ( gotEvent ) {
  204.             /* make sure we have the right cursor before handling the event */
  205.             AdjustCursor(event.where, cursorRgn);
  206.             DoEvent(&event);
  207.         }
  208.         /*    If you are using modeless dialogs that have editText items,
  209.             you will want to call IsDialogEvent to give the caret a chance
  210.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  211.             for a non-NIL value before calling IsDialogEvent. */
  212.     } while ( true );    /* loop forever; we quit via ExitToShell */
  213. } /*EventLoop*/
  214.  
  215.  
  216. /* Do the right thing for an event. Determine what kind of event it is, and call
  217.  the appropriate routines. */
  218.  
  219. #pragma segment Main
  220. void DoEvent(event)
  221.     EventRecord    *event;
  222. {
  223.     short        part, err;
  224.     WindowPtr    window;
  225.     Boolean        hit;
  226.     char        key;
  227.     Point        aPoint;
  228.  
  229.     switch ( event->what ) {
  230.         case mouseDown:
  231.             part = FindWindow(event->where, &window);
  232.             switch ( part ) {
  233.                 case inMenuBar:                /* process a mouse menu command (if any) */
  234.                     AdjustMenus();
  235.                     DoMenuCommand(MenuSelect(event->where));
  236.                     break;
  237.                 case inSysWindow:            /* let the system handle the mouseDown */
  238.                     SystemClick(event, window);
  239.                     break;
  240.                 case inContent:
  241.                     if ( window != FrontWindow() ) {
  242.                         SelectWindow(window);
  243.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  244.                     } else
  245.                         DoContentClick(window);
  246.                     break;
  247.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  248.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  249.                     break;
  250.                 case inGrow:
  251.                     break;
  252.                 case inZoomIn:
  253.                 case inZoomOut:
  254.                     hit = TrackBox(window, event->where, part);
  255.                     if ( hit ) {
  256.                         SetPort(window);                /* the window must be the current port... */
  257.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  258.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  259.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  260.                     }
  261.                     break;
  262.             }
  263.             break;
  264.         case keyDown:
  265.         case autoKey:                        /* check for menukey equivalents */
  266.             key = event->message & charCodeMask;
  267.             if ( event->modifiers & cmdKey )            /* Command key down */
  268.                 if ( event->what == keyDown ) {
  269.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  270.                     DoMenuCommand(MenuKey(key));
  271.                 }
  272.             break;
  273.         case activateEvt:
  274.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  275.             break;
  276.         case updateEvt:
  277.             DoUpdate((WindowPtr) event->message);
  278.             break;
  279.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  280.             to a diskEvt, so that the user can format a floppy. */
  281.         case diskEvt:
  282.             if ( HiWord(event->message) != noErr ) {
  283.                 SetPt(&aPoint, kDILeft, kDITop);
  284.                 err = DIBadMount(aPoint, event->message);
  285.             }
  286.             break;
  287.         case kOSEvent:
  288.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  289.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  290.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  291.                     gInBackground = (event->message & kResumeMask) == 0;
  292.                     DoActivate(FrontWindow(), !gInBackground);
  293.                     break;
  294.             }
  295.             break;
  296.     }
  297. } /*DoEvent*/
  298.  
  299.  
  300. /*    Change the cursor's shape, depending on its position. This also calculates the region
  301.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  302.     that region, an event would be generated, causing this routine to be called,
  303.     allowing us to change the region to the region the mouse is currently in. If
  304.     there is more to the event than just “the mouse moved”, we get called before the
  305.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  306.     this is called again before we     fall back into WNE. */
  307.  
  308. #pragma segment Main
  309. void AdjustCursor(mouse,region)
  310.     Point        mouse;
  311.     RgnHandle    region;
  312. {
  313.     WindowPtr    window;
  314.     RgnHandle    arrowRgn;
  315.     RgnHandle    plusRgn;
  316.     Rect        globalPortRect;
  317.  
  318.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  319.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  320.         /* calculate regions for different cursor shapes */
  321.         arrowRgn = NewRgn();
  322.         plusRgn = NewRgn();
  323.  
  324.         /* start with a big, big rectangular region */
  325.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  326.  
  327.         /* calculate plusRgn */
  328.         if ( IsAppWindow(window) ) {
  329.             SetPort(window);    /* make a global version of the viewRect */
  330.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  331.             globalPortRect = window->portRect;
  332.             RectRgn(plusRgn, &globalPortRect);
  333.             SectRgn(plusRgn, window->visRgn, plusRgn);
  334.             SetOrigin(0, 0);
  335.         }
  336.  
  337.         /* subtract other regions from arrowRgn */
  338.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  339.  
  340.         /* change the cursor and the region parameter */
  341.         if ( PtInRgn(mouse, plusRgn) ) {
  342.             SetCursor(*GetCursor(plusCursor));
  343.             CopyRgn(plusRgn, region);
  344.         } else {
  345.             SetCursor(&qd.arrow);
  346.             CopyRgn(arrowRgn, region);
  347.         }
  348.  
  349.         /* get rid of our local regions */
  350.         DisposeRgn(arrowRgn);
  351.         DisposeRgn(plusRgn);
  352.     }
  353. } /*AdjustCursor*/
  354.  
  355.  
  356. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  357.     it will return either a pending event or a null event. In either case,
  358.     the where field of the event record will contain the current position
  359.     of the mouse in global coordinates and the modifiers field will reflect
  360.     the current state of the modifiers. Another way to get the global
  361.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  362.     being sure that thePort is set to a valid port. */
  363.  
  364. #pragma segment Main
  365. void GetGlobalMouse(mouse)
  366.     Point    *mouse;
  367. {
  368.     EventRecord    event;
  369.     
  370.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  371.     *mouse = event.where;                /* just the mouse position */
  372. } /*GetGlobalMouse*/
  373.  
  374.  
  375. /*    This is called when an update event is received for a window.
  376.     It calls DrawWindow to draw the contents of an application window.
  377.     As an effeciency measure that does not have to be followed, it
  378.     calls the drawing routine only if the visRgn is non-empty. This
  379.     will handle situations where calculations for drawing or drawing
  380.     itself is very time-consuming. */
  381.  
  382. #pragma segment Main
  383. void DoUpdate(window)
  384.     WindowPtr    window;
  385. {
  386.     if ( IsAppWindow(window) ) {
  387.         BeginUpdate(window);                /* this sets up the visRgn */
  388.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  389.             DrawWindow(window);
  390.         EndUpdate(window);
  391.     }
  392. } /*DoUpdate*/
  393.  
  394.  
  395. /*    This is called when a window is activated or deactivated.
  396.     In Sample, the Window Manager's handling of activate and
  397.     deactivate events is sufficient. Other applications may have
  398.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  399.  
  400. #pragma segment Main
  401. void DoActivate(window, becomingActive)
  402.     WindowPtr    window;
  403.     Boolean        becomingActive;
  404. {
  405.     if ( IsAppWindow(window) ) {
  406.         if ( becomingActive )
  407.             /* do whatever you need to at activation */ ;
  408.         else
  409.             /* do whatever you need to at deactivation */ ;
  410.     }
  411. } /*DoActivate*/
  412.  
  413.  
  414. /*    This is called when a mouse-down event occurs in the content of a window.
  415.     Other applications might want to call FindControl, TEClick, etc., to
  416.     further process the click. */
  417.  
  418. #pragma segment Main
  419. void DoContentClick(window)
  420.     WindowPtr    window;
  421. {
  422.     SetLight(window, ! gStopped);
  423. } /*DoContentClick*/
  424.  
  425.  
  426. /* Draw the contents of the application window. We do some drawing in color, using
  427.    Classic QuickDraw's color capabilities. This will be black and white on old
  428.    machines, but color on color machines. At this point, the window’s visRgn
  429.    is set to allow drawing only where it needs to be done. */
  430.  
  431. #pragma segment Main
  432. void DrawWindow(window)
  433.     WindowPtr    window;
  434. {
  435.     SetPort(window);
  436.  
  437.     EraseRect(&window->portRect);    /* clear out any garbage that may linger */
  438.     if ( gStopped )                    /* draw a red (or white) stop light */
  439.         ForeColor(redColor);
  440.     else
  441.         ForeColor(whiteColor);
  442.     PaintOval(&gStopRect);
  443.     ForeColor(blackColor);
  444.     FrameOval(&gStopRect);
  445.     if ( ! gStopped )                /* draw a green (or white) go light */
  446.         ForeColor(greenColor);
  447.     else
  448.         ForeColor(whiteColor);
  449.     PaintOval(&gGoRect);
  450.     ForeColor(blackColor);
  451.     FrameOval(&gGoRect);
  452. } /*DrawWindow*/
  453.  
  454.  
  455. /*    Enable and disable menus based on the current state.
  456.     The user can only select enabled menu items. We set up all the menu items
  457.     before calling MenuSelect or MenuKey, since these are the only times that
  458.     a menu item can be selected. Note that MenuSelect is also the only time
  459.     the user will see menu items. This approach to deciding what enable/
  460.     disable state a menu item has the advantage of concentrating all
  461.     the decision-making in one routine, as opposed to being spread throughout
  462.     the application. Other application designs may take a different approach
  463.     that is just as valid. */
  464.  
  465. #pragma segment Main
  466. void AdjustMenus()
  467. {
  468.     WindowPtr    window;
  469.     MenuHandle    menu;
  470.  
  471.     window = FrontWindow();
  472.  
  473.     menu = GetMHandle(mFile);
  474.     if ( IsDAWindow(window) )        /* we can allow desk accessories to be closed from the menu */
  475.         EnableItem(menu, iClose);
  476.     else
  477.         DisableItem(menu, iClose);    /* but not our traffic light window */
  478.  
  479.     menu = GetMHandle(mEdit);
  480.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  481.         EnableItem(menu, iUndo);
  482.         EnableItem(menu, iCut);
  483.         EnableItem(menu, iCopy);
  484.         EnableItem(menu, iClear);
  485.         EnableItem(menu, iPaste);
  486.     } else {                        /* …but we don’t use it */
  487.         DisableItem(menu, iUndo);
  488.         DisableItem(menu, iCut);
  489.         DisableItem(menu, iCopy);
  490.         DisableItem(menu, iClear);
  491.         DisableItem(menu, iPaste);
  492.     }
  493.  
  494.     menu = GetMHandle(mLight);
  495.     if ( IsAppWindow(window) ) {    /* we know that it must be the traffic light */
  496.         EnableItem(menu, iStop);
  497.         EnableItem(menu, iGo);
  498.     } else {
  499.         DisableItem(menu, iStop);
  500.         DisableItem(menu, iGo);
  501.     }
  502.     CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
  503.     CheckItem(menu, iGo, ! gStopped);
  504. } /*AdjustMenus*/
  505.  
  506.  
  507. /*    This is called when an item is chosen from the menu bar (after calling
  508.     MenuSelect or MenuKey). It performs the right operation for each command.
  509.     It is good to have both the result of MenuSelect and MenuKey go to
  510.     one routine like this to keep everything organized. */
  511.  
  512. #pragma segment Main
  513. void DoMenuCommand(menuResult)
  514.     long        menuResult;
  515. {
  516.     short        menuID;                /* the resource ID of the selected menu */
  517.     short        menuItem;            /* the item number of the selected menu */
  518.     short        itemHit;
  519.     Str255        daName;
  520.     short        daRefNum;
  521.     Boolean        handledByDA;
  522.  
  523.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  524.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  525.     switch ( menuID ) {
  526.         case mApple:
  527.             switch ( menuItem ) {
  528.                 case iAbout:        /* bring up alert for About */
  529.                     itemHit = Alert(rAboutAlert, nil);
  530.                     break;
  531.                 default:            /* all non-About items in this menu are DAs */
  532.                     /* type Str255 is an array in MPW 3 */
  533.                     GetItem(GetMHandle(mApple), menuItem, daName);
  534.                     daRefNum = OpenDeskAcc(daName);
  535.                     break;
  536.             }
  537.             break;
  538.         case mFile:
  539.             switch ( menuItem ) {
  540.                 case iClose:
  541.                     DoCloseWindow(FrontWindow());
  542.                     break;
  543.                 case iQuit:
  544.                     Terminate();
  545.                     break;
  546.             }
  547.             break;
  548.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  549.             handledByDA = SystemEdit(menuItem-1);    /* since we don’t do any Editing */
  550.             break;
  551.         case mLight:
  552.             switch ( menuItem ) {
  553.                 case iStop:
  554.                     SetLight(FrontWindow(), true);
  555.                     break;
  556.                 case iGo:
  557.                     SetLight(FrontWindow(), false);
  558.                     break;
  559.             }
  560.             break;
  561.     }
  562.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  563. } /*DoMenuCommand*/
  564.  
  565.  
  566. /* Change the setting of the light. */
  567.  
  568. #pragma segment Main
  569. void SetLight( window, newStopped )
  570.     WindowPtr    window;
  571.     Boolean        newStopped;
  572. {
  573.     if ( newStopped != gStopped ) {
  574.         gStopped = newStopped;
  575.         SetPort(window);
  576.         InvalRect(&window->portRect);
  577.     }
  578. } /*SetLight*/
  579.  
  580.  
  581. /* Close a window. This handles desk accessory and application windows. */
  582.  
  583. /*    1.01 - At this point, if there was a document associated with a
  584.     window, you could do any document saving processing if it is 'dirty'.
  585.     DoCloseWindow would return true if the window actually closed, i.e.,
  586.     the user didn’t cancel from a save dialog. This result is handy when
  587.     the user quits an application, but then cancels the save of a document
  588.     associated with a window. */
  589.  
  590. #pragma segment Main
  591. Boolean DoCloseWindow(window)
  592.     WindowPtr    window;
  593. {
  594.     if ( IsDAWindow(window) )
  595.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  596.     else if ( IsAppWindow(window) )
  597.         CloseWindow(window);
  598.     return true;
  599. } /*DoCloseWindow*/
  600.  
  601.  
  602. /**************************************************************************************
  603. *** 1.01 DoCloseBehind(window) was removed ***
  604.  
  605.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  606.     and not having to worry about updating the windows, but it suffered
  607.     from a fatal flaw. If a desk accessory owned two windows, it would
  608.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  609.     got around to calling DoCloseWindow for that other window that was already
  610.     closed, things would go very poorly. Another option would be to have a
  611.     procedure, GetRearWindow, that would go through the window list and return
  612.     the last window. Instead, we decided to present the standard approach
  613.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  614.     has a potential benefit in that the window whose document needs to be saved
  615.     may be visible since it is the front window, therefore decreasing the
  616.     chance of user confusion. For aesthetic reasons, the windows in the
  617.     application should be checked for updates periodically and have the
  618.     updates serviced.
  619. **************************************************************************************/
  620.  
  621.  
  622. /* Clean up the application and exit. We close all of the windows so that
  623.  they can update their documents, if any. */
  624.  
  625. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  626.     shell, but will return instead. */
  627.  
  628. #pragma segment Main
  629. void Terminate()
  630. {
  631.     WindowPtr    aWindow;
  632.     Boolean        closed;
  633.     
  634.     closed = true;
  635.     do {
  636.         aWindow = FrontWindow();                /* get the current front window */
  637.         if (aWindow != nil)
  638.             closed = DoCloseWindow(aWindow);    /* close this window */    
  639.     }
  640.     while (closed && (aWindow != nil));
  641.     if (closed)
  642.         ExitToShell();                            /* exit if no cancellation */
  643. } /*Terminate*/
  644.  
  645.  
  646. /*    Set up the whole world, including global variables, Toolbox managers,
  647.     and menus. We also create our one application window at this time.
  648.     Since window storage is non-relocateable, how and when to allocate space
  649.     for windows is very important so that heap fragmentation does not occur.
  650.     Because Sample has only one window and it is only disposed when the application
  651.     quits, we will allocate its space here, before anything that might be a locked
  652.     relocatable object gets into the heap. This way, we can force the storage to be
  653.     in the lowest memory available in the heap. Window storage can differ widely
  654.     amongst applications depending on how many windows are created and disposed. */
  655.  
  656. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  657.     this module. If an error is detected, instead of merely doing an ExitToShell,
  658.     which leaves the user without much to go on, we call AlertUser, which puts
  659.     up a simple alert that just says an error occurred and then calls ExitToShell.
  660.     Since there is no other cleanup needed at this point if an error is detected,
  661.     this form of error- handling is acceptable. If more sophisticated error recovery
  662.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  663.  
  664. #pragma segment Initialize
  665. void Initialize()
  666. {
  667.     Handle        menuBar;
  668.     WindowPtr    window;
  669.     long        total, contig;
  670.     EventRecord event;
  671.     short        count;
  672.  
  673.     gInBackground = false;
  674.  
  675.     InitGraf((Ptr) &qd.thePort);
  676.     InitFonts();
  677.     InitWindows();
  678.     InitMenus();
  679.     TEInit();
  680.     InitDialogs(nil);
  681.     InitCursor();
  682.     
  683.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  684.          if you are using it. */
  685.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  686.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  687.         of checking for port availability themselves. */
  688.     
  689.     /*    This next bit of code is necessary to allow the default button of our
  690.         alert be outlined.
  691.         1.02 - Changed to call EventAvail so that we don't lose some important
  692.         events. */
  693.      
  694.     for (count = 1; count <= 3; count++)
  695.         EventAvail(everyEvent, &event);
  696.     
  697.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  698.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  699.         call to SysEnvirons by calling it after initializing AppleTalk. */
  700.      
  701.     SysEnvirons(kSysEnvironsVersion, &gMac);
  702.     
  703.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  704.     
  705.     if (gMac.machineType < 0) AlertUser();
  706.     
  707.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  708.         in TrapAvailable if a tool trap value is out of range. */
  709.         
  710.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  711.  
  712.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  713.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  714.         MultiFinder we needed. This did not work well because it assumed too much about
  715.         the relationship between what we asked MultiFinder for and what we would actually
  716.         get back, as well as how to measure it. Instead, we will use an alternate
  717.         method comprised of two steps. */
  718.      
  719.     /*    It is better to first check the size of the application heap against a value
  720.         that you have determined is the smallest heap the application can reasonably
  721.         work in. This number should be derived by examining the size of the heap that
  722.         is actually provided by MultiFinder when the minimum size requested is used.
  723.         The derivation of the minimum size requested from MultiFinder is described
  724.         in Sample.h. The check should be made because the preferred size can end up
  725.         being set smaller than the minimum size by the user. This extra check acts to
  726.         insure that your application is starting from a solid memory foundation. */
  727.      
  728.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  729.     
  730.     /*    Next, make sure that enough memory is free for your application to run. It
  731.         is possible for a situation to arise where the heap may have been of required
  732.         size, but a large scrap was loaded which left too little memory. To check for
  733.         this, call PurgeSpace and compare the result with a value that you have determined
  734.         is the minimum amount of free memory your application needs at initialization.
  735.         This number can be derived several different ways. One way that is fairly
  736.         straightforward is to run the application in the minimum size configuration
  737.         as described previously. Call PurgeSpace at initialization and examine the value
  738.         returned. However, you should make sure that this result is not being modified
  739.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  740.         PurgeSpace. Make sure to remove that call before shipping, though. */
  741.     
  742.     /* ZeroScrap(); */
  743.  
  744.     PurgeSpace(&total, &contig);
  745.     if (total < kMinSpace) AlertUser();
  746.  
  747.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  748.         to check memory is that we can now give the user an alert to tell him/her what
  749.         happened. Although it is possible that the memory situation could be worsened by
  750.         displaying an alert, MultiFinder would gracefully exit the application with
  751.         an informative alert if memory became critical. Here we are acting more
  752.         in a preventative manner to avoid future disaster from low-memory problems. */
  753.  
  754.     /*     we will allocate our own window storage instead of letting the Window
  755.         Manager do it because GetNewWindow may load in temp. resources before
  756.         making the NewPtr call, and this can lead to heap fragmentation. */
  757.     window = (WindowPtr) NewPtr(sizeof(WindowRecord));
  758.     if ( window == nil ) AlertUser();
  759.     window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
  760.  
  761.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  762.     if ( menuBar == nil ) AlertUser();
  763.     SetMenuBar(menuBar);                    /* install menus */
  764.     DisposHandle(menuBar);
  765.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  766.     DrawMenuBar();
  767.     
  768.     gStopped = true;
  769.     if ( !GoGetRect(rStopRect, &gStopRect) )
  770.         AlertUser();                        /* the stop light rectangle */
  771.     if ( !GoGetRect(rGoRect, &gGoRect) )
  772.         AlertUser();                        /* the go light rectangle */
  773. } /*Initialize*/
  774.  
  775.  
  776. /*    This utility loads the global rectangles that are used by the window
  777.     drawing routines. It shows how the resource manager can be used to hold
  778.     values in a convenient manner. These values are then easily altered without
  779.     having to re-compile the source code. In this particular case, we know
  780.     that this routine is being called at initialization time. Therefore,
  781.     if a failure occurs here, we will assume that the application is in such
  782.     bad shape that we should just exit. Your error handling may differ, but
  783.     the check should still be made. */
  784.     
  785. #pragma segment Initialize
  786. Boolean GoGetRect(rectID,theRect)
  787.     short    rectID;
  788.     Rect    *theRect;
  789. {
  790.     Handle        resource;
  791.     
  792.     resource = GetResource('RECT', rectID);
  793.     if ( resource != nil ) {
  794.         *theRect = **((Rect**) resource);
  795.         return true;
  796.     }
  797.     else
  798.         return false;
  799. } /* GoGetRect */
  800.  
  801.  
  802. /*    Check to see if a window belongs to the application. If the window pointer
  803.     passed was NIL, then it could not be an application window. WindowKinds
  804.     that are negative belong to the system and windowKinds less than userKind
  805.     are reserved by Apple except for windowKinds equal to dialogKind, which
  806.     mean it is a dialog.
  807.     1.02 - In order to reduce the chance of accidentally treating some window
  808.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  809.     is userKind. If you add different kinds of windows to Sample you'll need
  810.     to change how this all works. */
  811.  
  812. #pragma segment Main
  813. Boolean IsAppWindow(window)
  814.     WindowPtr    window;
  815. {
  816.     short        windowKind;
  817.  
  818.     if ( window == nil )
  819.         return false;
  820.     else {    /* application windows have windowKinds = userKind (8) */
  821.         windowKind = ((WindowPeek) window)->windowKind;
  822.         return (windowKind == userKind);
  823.     }
  824. } /*IsAppWindow*/
  825.  
  826.  
  827. /* Check to see if a window belongs to a desk accessory. */
  828.  
  829. #pragma segment Main
  830. Boolean IsDAWindow(window)
  831.     WindowPtr    window;
  832. {
  833.     if ( window == nil )
  834.         return false;
  835.     else    /* DA windows have negative windowKinds */
  836.         return ((WindowPeek) window)->windowKind < 0;
  837. } /*IsDAWindow*/
  838.  
  839.  
  840. /*    Check to see if a given trap is implemented. This is only used by the
  841.     Initialize routine in this program, so we put it in the Initialize segment.
  842.     The recommended approach to see if a trap is implemented is to see if
  843.     the address of the trap routine is the same as the address of the
  844.     Unimplemented trap. */
  845. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  846.     if a ToolTrap is out of range of a pre-MacII ROM. */
  847.  
  848. #pragma segment Initialize
  849. Boolean TrapAvailable(tNumber,tType)
  850.     short        tNumber;
  851.     TrapType    tType;
  852. {
  853.     if ( ( tType == ToolTrap ) &&
  854.         ( gMac.machineType > envMachUnknown ) &&
  855.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  856.         tNumber = tNumber & 0x03FF;
  857.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  858.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  859.     }
  860.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  861. } /*TrapAvailable*/
  862.  
  863.  
  864. /*    Display an alert that tells the user an error occurred, then exit the program.
  865.     This routine is used as an ultimate bail-out for serious errors that prohibit
  866.     the continuation of the application. Errors that do not require the termination
  867.     of the application should be handled in a different manner. Error checking and
  868.     reporting has a place even in the simplest application. The error number is used
  869.     to index an 'STR#' resource so that a relevant message can be displayed. */
  870.  
  871. #pragma segment Main
  872. void AlertUser()
  873. {
  874.     short        itemHit;
  875.  
  876.     SetCursor(&qd.arrow);
  877.     itemHit = Alert(rUserAlert, nil);
  878.     ExitToShell();
  879. } /* AlertUser */
  880.  
  881.  
  882. #pragma trace off
  883. Boolean BreakHere ( void ) {
  884.     return true;
  885.     }
  886.